<?php
/**
 * M端理财
 * User: lyc
 * Date: 2017/01/04
 * Time: 19:16
 */
class WebInvestController extends BaseController
{

    //理财列表(暂时没用)
    public function FinancingList(){
        $info = ApiInvestService::instance()->FinancingListWeb();//普通标列表
        $img = ApiInvestService::instance()->FinancingBanner();//理财Banner
        foreach($info as $key => $info1){
            $info[$key]->balance_amount = number_format(($info[$key]->amount  - $info[$key]->amount_collect )/100 , 0);
            if($info[$key]->status == 'REPAYING'){
                $info[$key]->status = 'FULLSCALE';
            }
        }
        return $this->view('webview.gpw_finacing')->with(['info' => $info,'banner'=>$img]);
    }
    /**
     * @author lyc
     * @date 2016-12-23 14:32
     * @return bool
     */
    public function FinancingList1(){
        //我要理财
        $paramObj               =          new stdClass();
        $paramObj->page        =          $this->getParam('page');//页数
        $data = [];
        try{
            $info = ApiInvestService::instance()->FinancingList($paramObj->page);//普通标列表
            $img = ApiInvestService::instance()->FinancingBanner();//理财Banner
            foreach($info as $key => $info1){
                $info[$key]->balance_amount = number_format(($info[$key]->amount  - $info[$key]->amount_collect )/100 , 0);
                if($info[$key]->status == 'REPAYING'){
                    $info[$key]->status = 'FULLSCALE';
                }
            }
            $data['info'] = $info;
            $data['img'] = $img;
            $this->rest->success($data, ErrorCodeEnum::STATUS_SUCCESS, "标的列表!");
        }catch(Exception $e){
            $this->rest->error($e->getMessage(), $e->getCode(),new stdClass());
        }
    }
    //理财详情
    public function FinancingDetails(){
        $paramObj               =          new stdClass();
        $paramObj->auto_id        =          $this->getParam('auto_id');//标的ID
            $info = ApiInvestService::instance()->GetApiFinancingDetails($paramObj);
            if($info->refund_type == 'ONE_TIME_SERVICING'){
                $info->refund_type = "一次性还本付息";
            }elseif($info->refund_type == 'FIRSEINTREST_LASTPRICIPAL'){
                $info->refund_type = "先息后本";
            }elseif($info->refund_type == 'FIXED_PAYMENT_MORTGAGE'){
                $info->refund_type = "等额本息";
            }else{
                $info->refund_type = "等额本金";
            }
            $info->amount = $info->amount/1000000;
            $info->begin_amount_sx = $info->begin_amount_sx/10000;
            $info->jindu  =  $info->amount_collect / (($info->amount)*1000000) * 100;
            $info->balance_amount  =  number_format(($info->amount *1000000 - $info->amount_collect)/100,0);
            $info->today_time = time();
            $info->qixi_time =  time() ;
            $info->refund_time =time() + $info->deadline * 24 *3600;

        //项目简介
        $sp = ApiInvestService::instance()->GetSP($paramObj);
        $file = ApiInvestService::instance()->GetFile($paramObj);
        //投资记录
        $invest =  ApiInvestService::instance()->GetInvest($paramObj);
        foreach($invest as $key =>$in){
            $phone= ItemService::instance()->GetUserIphone($in->user_id);
            $invest[$key]->amount =number_format($invest[$key]->amount/100,0);
            if(empty($phone)){
                $invest[$key]->telephone = "无";
            }else{
                $invest[$key]->telephone =substr_replace($phone->telephone,'****',3,4);
            }
        }
        return $this->view('webview.gpw_finacing_details')->with(['info' => $info,'sp'=>$sp,'file'=>$file,'invest'=>$invest,'user_id'=>session_get(UserEnum::USER_INFO_USER_ID)]);
    }
    /**
     * 简介，常见问题，投标记录
     */
    public function FinancingDetailsJct(){
        $paramObj               =          new stdClass();
        $paramObj->auto_id        =          $this->getParam('auto_id');//标的ID
        $paramObj->type        =          $this->getParam('type');//类型
        $paramObj->page        =          $this->getParam('page');//页数
        try{
            if($paramObj->type == 1){
                $info = ApiInvestService::instance()->GetSP($paramObj);
                $file = ApiInvestService::instance()->GetFile($paramObj);
                $array=array();

                if(empty($info->business_ticket_img)){
                    $info->business_ticket_img ="";
                }else{
                    $info->business_ticket_img =$info->business_ticket_img;
                }if(empty($file->prove_file)){

                }else{
                    $array[] =$file->prove_file;
                }if(empty($file->prove_file1)){

                }else{
                    $array[] =$file->prove_file1;
                }if(empty($file->prove_file2)){

                }else{
                    $array[] =$file->prove_file2;
                }if(empty($file->prove_file3)){

                }else{
                    $array[] =$file->prove_file3;
                }if(empty($file->prove_file4)){

                }else{
                    $array[] =$file->prove_file4;
                }if(empty($file->prove_file5)){

                }else{
                    $array[] = $file->prove_file5;
                }
                $info->file = $array;
            }elseif($paramObj->type == 2){
                $info =  ApiInvestService::instance()->GetInterlocution();
            }elseif($paramObj->type == 3){
                $info =  ApiInvestService::instance()->GetInvest($paramObj);
                foreach($info as $key =>$in){
                    $phone= ItemService::instance()->GetUserIphone($in->user_id);
                    $info[$key]->amount =number_format($info[$key]->amount/100,0);
                    if(empty($phone)){
                        $info[$key]->telephone = "无";
                    }else{
                        $info[$key]->telephone =substr_replace($phone->telephone,'****',3,4);
                    }
                }
            }else{
                $info ="";
            }
            $this->rest->success($info, ErrorCodeEnum::STATUS_SUCCESS, " 简介,常见问题,投标记录");
        }catch(Exception $e){
            $this->rest->error($e->getMessage(), $e->getCode(),new stdClass());
        }

    }


    //投资页面
    public function Invest(){
        $paramObj               =          new stdClass();
        $paramObj->auto_id        =          $this->getParam('auto_id');//标的ID
        $info = ApiInvestService::instance()->GetApiFinancingDetails($paramObj);
        return $this->view('webview.gpw_finacing_gofinal')->with(['auto_id' => $paramObj->auto_id,'rate'=>$info->rate_loaner,'title'=>$info->title]);
    }

    /**
     * 体验标详情
     * @return int
     */
    public function ExperDetail()
    {
        $exper_id     =   $this->getParam('exper_id');                                   //体验标id
        $user_id = session_get(UserEnum::USER_INFO_USER_ID);
        $data = InvestService::instance()->Tiyan();
        $amount = InvestService::instance()->ExperAllAmount($exper_id);                  //融资金额总数
        if(!empty($user_id)){
            $user_info = InvestService::instance()->ExperInvest($exper_id,$user_id);
        }

        if(!empty($user_info)){

            $all_amount ='';
            foreach($amount as $k=>$v){
                $all_amount+= $v->exper_amount;
            }
            return $this->view('webview.gpw_finacing_nhitem')->with(['tiyan'=>$data,'all_amount'=>$all_amount,'user_invest_record'=>$user_info]);
        }else if(!empty($amount)){
            $all_amount ='';
            foreach($amount as $k=>$v){
                $all_amount+= $v->exper_amount;
            }
            return $this->view('webview.gpw_finacing_nhitem')->with(['tiyan'=>$data,'all_amount'=>$all_amount]);
        }else{
            return $this->view('webview.gpw_finacing_nhitem')->with(['tiyan'=>$data]);
        }

    }

    /**
     * 体验金投资
     * @return int
     */
    public function ExperInvest()
    {
        $exper_id     =   $this->getParam('exper_id');          //体验标id
        $user_id      =   $this->getParam('user_id');           //用户id
        $exper_amount =   $this->getParam('exper_amount');      //体验投资金额

        $now = time();
        $begin_time = strtotime(date('Y-m-d', time()))+36000;
        if($now>$begin_time){
            $data = InvestService::instance()->ExperInvest($exper_id,$user_id);
            $tiyan = InvestService::instance()->Tiyan();
            if($tiyan->is_valid == 1){
                if(empty($data)){
                    $data2 = InvestService::instance()->ExperInsert($exper_id,$user_id,$exper_amount);
                    if(!empty($data2)){
                        return 1;
                    }
                }else{
                    return 2;
                }
            }else{
                return 3;
            }
        }else{
            return 4;
        }

    }


    /**
     *投资展示
     *
     */
    public function FinancingDisplay()
    {
        $paramObj               =          new stdClass();
        $info               =          new stdClass();
        $paramObj->auto_id         =          $this->getParam('item_id');
        $paramObj->user_id         =          session_get(UserEnum::USER_INFO_USER_ID);
        $award = array();
        $ticket = array();
        if (empty($paramObj->user_id)){
            throw new Exception('用户未登录！', ErrorCodeEnum::STATUS_ERROR_NOT_LOGIN);
        }
        try{
            $data = ApiInvestService::instance()->GetApiFinancingDetails($paramObj);
            $fund_info = WebUserService::instance()->WebUserAccounts($paramObj->user_id);
            $balance_amount  =  number_format(($data->amount - $data->amount_collect)/100,0);
            $paramObj->qixian  = $data->deadline;
            if($data->is_award == 1){
                $award = ApiInvestService::instance()->GetApiAward($paramObj);//红包
                foreach($award as $key =>$award1){
                    $award[$key]->amount = $award[$key]->amount/100;
                    $award[$key]->restrict_amount = $award[$key]->restrict_amount/100;
                }
            }else{
                $award = [];
            }

            if($data->is_takeup == 1){
                $ticket = InvestService::instance()->SelectTicket($paramObj);//是否存在加息券
                foreach($ticket as $key =>$ticket1){
                    $ticket[$key]->rate = $ticket[$key]->rate/100;
                    if($ticket[$key]->restrict_time == 0){

                        $ticket[$key]->restrict_time ="适用所有投资项目";
                    }
                }
            }else{
                $ticket = [];
            }

            $info->balance_amount = $balance_amount;
            $info->item_id = $paramObj->auto_id;
            $info->rate_loaner = $data->rate_loaner;
            $info->begin_amount = $data->begin_amount;
            $info->begin_amount_sx = $data->begin_amount_sx;
            $info->deadline = $data->deadline;
            $info->type = $data->type;
            $info->award = $award;
            $info->ticket = $ticket;
            $info->account = $fund_info['money'];
            $this->rest->success($info, ErrorCodeEnum::STATUS_SUCCESS, "投标展示");
        }catch(Exception $e){
            $this->rest->error($e->getMessage(), $e->getCode(),new stdClass());
        }
    }
    /**
     * 确认投资
     */
    public function ConfirmInvest(){
        $paramObj               =          new stdClass();
        $invest_info               =          new stdClass();
        $paramObj->item_id         =          $this->getParam('item_id');
        $paramObj->rate           =   $this->getParam('rate');      //利率
        $paramObj->amount           =   $this->getParam('amount') * 100 ; //输入的金额
        $paramObj->money           =   $paramObj->amount /100;      //输入的金额
        $paramObj->award_id           =   $this->getParam('award_id')?$this->getParam('award_id'):0;      //红包id
        $paramObj->ticket_id           =   $this->getParam('ticket_id')?$this->getParam('ticket_id'):0;      //红包id
        $paramObj->user_id         =      session_get(UserEnum::USER_INFO_USER_ID);
        if (empty($paramObj->item_id) || empty($paramObj->amount) ||  empty($paramObj->user_id) || empty($paramObj->money)){
            $message="参数不足";
            $this->rest->error($message, ErrorCodeEnum::STATUS_ERROR_PARAMS_MUST, "投资失败");
        }
        if (empty($paramObj->user_id)){
            $message="用户未登录";
            $this->rest->error($message, ErrorCodeEnum::STATUS_ERROR_NOT_LOGIN, "投资失败");
        }
        $iscard = InvestService::instance()->Iscard($paramObj);//验证实名
        if($iscard->is_idcard == 0){
            $message="您还未在平台实名，请前去实名";
            $this->rest->error($message, ErrorCodeEnum::STATUS_ERROR_NOT_ISCARD, "投资失败");
        }
        $fund = UserService::instance()->GetFund($paramObj->user_id);//是否需要充值
        if (!$fund)
        {
            $message="资金账户，异常请稍候再试";
            $this->rest->error($message, ErrorCodeEnum::STATUS_ERROR_NOT_ACCOUNT_ANOMALIES, "投资失败");
        }elseif($paramObj->money > $fund->money_unit ){
            $message="账户余额不足，请充值";
            $this->rest->error($message, ErrorCodeEnum::STATUS_ERROR_NOT_PLEASE_RECHARGE, "投资失败");
        }
        $item = ItemService::instance()->IsItem($paramObj->item_id);//是否存在该项目，项目状态是否正确
        // 未找到项目
        if (!$item)
        {
            $message="未找到该标的";
            $this->rest->error($message, ErrorCodeEnum::STATUS_ERROR_NOT_FOUND_ITEM, "投资失败");
        }elseif( $item->status != 'COLLECTING'){
            $message="此项目已募集完毕, 请选择其它项目进行投资";
            $this->rest->error($message, ErrorCodeEnum::STATUS_ERROR_NOT_FINISHED, "投资失败");
        }
        //检查最低起投
        if($paramObj->money < $item->begin_amount){
            $message="此金额低于最低可投金额，请重新输入";
            $this->rest->error($message, ErrorCodeEnum::STATUS_ERROR_NOT_BU_DAO, "投资失败");
        }
        //检查最高起投
        if($item->begin_amount_sx !=0){
            if($paramObj->money > $item->begin_amount_sx){
                $message="此金额高于最高可投金额，请重新输入";
                $this->rest->error($message, ErrorCodeEnum::STATUS_ERROR_NOT_GAO_YU, "投资失败");
            }
        }

        // 检查项目投资金额是否足够
        $canBeAmount = $item->amount - $item->amount_collect;
        if ($canBeAmount < $paramObj->money * 100)
        {
            $message= '投资金额超过项目可投金额, 目前此项目最多能投'.(number_format($canBeAmount/100)).'元';
            $this->rest->error($message, ErrorCodeEnum::STATUS_ERROR_NOT_MUCH_MONEY, "投资失败");
        }
        // 检查剩余金额不能少于最低可投金额
        $limitBeAmount = $canBeAmount -  $paramObj->money *100;

        if ($limitBeAmount < $item->begin_amount *100 && $limitBeAmount > 0)
        {
            $message= "您投标后，标的剩余可投金额将少于 {$item->begin_amount} 元。您可选择一锤定音或投资 ".number_format(($canBeAmount/100-$item->begin_amount))." 元";
            $this->rest->error($message, ErrorCodeEnum::STATUS_ERROR_NOT_LITTER_MONEY, "投资失败");
        }
        if($item->type == 'NEWBIE'){
            $isInvest = InvestService::instance()->IsInvest($paramObj->item_id,$paramObj->user_id);//检查该用户是否投过新手标
            // 如果是第一次投资
            if(empty($isInvest))
            {
                $trade_id = InvestService::instance()->Confirminvest($paramObj);//插入投资记录
                $trade = InvestService::instance()->SelectInvest($trade_id);    //查询投资记录
                $result = InvestService::instance()->success($trade->trade_num);//系列操作
                if($result['code'] == 200){
                    $amount = $result['amount'];
                    $this->rest->success($amount, ErrorCodeEnum::STATUS_SUCCESS, "投资成功");
                }else{
                    $this->rest->error("", ErrorCodeEnum::STATUS_ERROR_INVEST_FILD, "投资失败");
                }
            }else{
                $message = "此标的为新手专享，仅限未投资过的新用户投资，每人限投一次";
                $this->rest->error("", ErrorCodeEnum::STATUS_ERROR_NOT_NEWBIE_ONE, "投资失败");
            }
        }else{
            $trade_id = InvestService::instance()->Confirminvest($paramObj);//插入投资记录
            $trade = InvestService::instance()->SelectInvest($trade_id);    //查询投资记录
            $result = InvestService::instance()->success($trade->trade_num);//系列操作
           // $date= ApiUserService::instance()->ApiUserAccounts();

            if($result['code'] == 200){
                $amount = $result['amount'];
                $this->rest->success($amount, ErrorCodeEnum::STATUS_SUCCESS, "投资成功");
            }else{
                $this->rest->error("", ErrorCodeEnum::STATUS_ERROR_INVEST_FILD, "投资失败");
            }
        }
    }
    //用户协议
    public function UserAgreement(){
        return $this->view('webview.gpw_agreement');
    }
    //投资协议
    public function InvestAgreement(){
        return $this->view('webview.gpw_invest_agreement');
    }
    //投资成功页面
    public function InvestSuccess(){
        $paramObj                 =          new stdClass();
        $paramObj->amount         =          $this->getParam('amount');
        return $this->view('webview.gpw_finacing_success')->with(['amount'=> $paramObj->amount]);
    }

    public function ExperSuccess()
    {
        $paramObj                 =          new stdClass();
        $paramObj->amount         =          $this->getParam('amount');

        return $this->view('webview.gpw_finacingitem_success')->with(['amount'=> $paramObj->amount]);
    }




}